package com.leenmvc.core.utils.file;

import cn.hutool.core.io.FileUtil;
import com.leenmvc.core.aop.proxy.ProxyUtil;
import com.leenmvc.core.dao.communal.BaseDao;
import com.leenmvc.core.enums.UploadPlace;
import com.leenmvc.core.exception.FileException;
import com.leenmvc.core.exception.ValidatorException;
import com.leenmvc.core.security.User;
import com.leenmvc.core.security.entity.core.SysFileUpload;
import com.leenmvc.core.utils.DateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * 文件上传操作的类
 */
public class UploadManager {

    private static BaseDao baseDao = ProxyUtil.getProxyDao()[0];

    /**
     * 文件上传到本地
     * 文件类型/日期精确到秒/
     *
     */
    public static SysFileUpload uploadToLocal(MultipartFile file) {
        String userDir = System.getProperty("user.dir");
        String yyyyMMddHH = DateUtils.format(System.currentTimeMillis(), "yyyyMMddHH");
        String originalFilename = file.getOriginalFilename();
        String[] fileArr = originalFilename.split("\\.");
        if(fileArr.length < 2) {
            throw new ValidatorException("文件上传失败，请选择带有后缀的文件");
        }
        String fileType = fileArr[1];
        String absoluteFile = new StringBuffer(userDir).append("/").append("upload").append("/").append(fileType).append("/").append(yyyyMMddHH).append("/").append(UUID.randomUUID()).append(".").append(fileType).toString();
        File realFile = new File(absoluteFile);
        try {
            File file1 = FileUtil.writeBytes(file.getBytes(), realFile);
            if(file1 != null) {
                SysFileUpload fileUpload = new SysFileUpload();
                fileUpload.setFileName(realFile.getName());
                fileUpload.setOriginalName(originalFilename);
                fileUpload.setFileSize(file.getSize());
                fileUpload.setFilePath(realFile.getAbsolutePath());
                fileUpload.setCreator(User.getId());
                fileUpload.setCreateDate(new Date());
                fileUpload.setStatus(2); // 2 表示未在用
                fileUpload.setPlace(UploadPlace.LOCAL.getCode()); // 表示在本地
                baseDao.insert(fileUpload);
                return fileUpload;
            }
        } catch (IOException e) {
            throw new FileException("文件上传失败，请检查文件是否符合上传条件", e);
        }
        return null;
    }

}
